package com.hncu.edu.info.manager.dao;

import com.hncu.edu.info.manager.domain.Student;

public class StudentDao implements BaseStudentDao{
    //创建学生数组
    private static Student[] arr = new Student[5];

    // 静态代码块（写类中构造外），便于测试
    static {
        Student stu1 = new Student("hncu001", "张三", "21", "1999-11-11");
        Student stu2 = new Student("hncu002", "李四", "20", "2000-11-11");
        arr[0] = stu1;
        arr[1] = stu2;
    }
    //空参构造
    public StudentDao() {

    }

    //添加学生
    public boolean addStudent(Student stu) {
        int Index = -1;
        //遍历数组，找空位
        for (int i = 0; i < arr.length; i++) {
            Student student = arr[i];
            if (student == null) {
                //如果找到空位，就让Index记录该索引值
                Index = i;
                break;
            }
        }
        if (Index == -1) {
            //数组内无空位了
            return false;
        } else {
            //存入学生对象
            arr[Index] = stu;
            return true;
        }
    }

    //查找学生
    public Student[] findAllStudent() {
        return arr;
    }

    //删除学生
    public void deleteStudentBySid(String sid) {
        //找到位置
        int Index = getIndex(sid);
        //删除
        arr[Index] = null;
    }

    //根据学号找位置
    public int getIndex(String sid) {
        //假设数组没有这个学号
        int Index = -1;
        //遍历数组
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if (stu != null && stu.getid().equals(sid)) {
                Index = i;
                break;
            }
        }
        return Index;
    }

    //修改学生
    public void updateStudent(Student stu) {
        //获取被修改学生学号
        String sid = stu.getid();
        //找到该学生的索引位置
        int Index = getIndex(sid);
        //添加新的学生对象进去
        arr[Index] = stu;
    }
}
